#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2020/07/29 20:48
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：

import device
import re
import timeEXT


def get_serial_number():
    serial_number = '12345678'
    while serial_number == "12345678":
        for device_info in device.get_device_serial_number().values():
            if device_info:
                serial_number = device_info[0]
                break
    return serial_number


# 加密成KEY
def encryption(time_str):
    # 转换时间无符号时间，反转时间串，转成16进制，每字节加18，每4位用-分割
    time_str = "".join(re.findall('\d*', time_str))
    fz = time_str[::-1]
    time_hex = int(fz, 16)
    hex_list = "".join([chr(ord(k) + 18) for k in (str(time_hex))])
    key = "-".join(re.findall('\w\w\w\w|\w+', hex_list))
    return key


# 解密成时间戳
def decrypt(key):
    try:
        key_hex = "".join(re.findall('\w*', key))
        key_str = "{:X}".format(int("".join([chr(ord(k) - 18) for k in key_hex])))[::-1]
        datetime_str = timeEXT.NumberToDateTimeStr(key_str)
        utc = timeEXT.StrToUtc(datetime_str)
        return utc
    except:
        return False


# 注册
def save_key(conn, key):
    serlal_number = get_serial_number()
    sql = "UPDATE register SET SN='{}',PASSWORD='{}'".format(serlal_number, key)
    return conn.execSql(sql)


# 增加30天试用
def add_register_day(conn):
    utc = decrypt(query_save_key(conn)['PASSWORD']) + 30 * 24 * 3600
    key = encryption(timeEXT.UtcToStr(utc))
    return save_key(conn, key)


# 查询key
def query_save_key(conn):
    sql = "SELECT NAME FROM SQLITE_MASTER WHERE TYPE='table' AND NAME='register'"
    data = conn.loadSql(sql)
    if not data:
        sql = "CREATE TABLE register (SN  TEXT(100), PASSWORD TEXT(500) )"
        conn.execSql(sql)
        serlal_number = get_serial_number()
        now_time = timeEXT.UtcToStr(timeEXT.GetUtc() + 30 * 24 * 3600)
        key = encryption(now_time)
        sql = "INSERT INTO register (SN,PASSWORD) VALUES ('{}','{}')".format(serlal_number, key)
        conn.execSql(sql)
        return query_save_key(conn)
    else:
        sql = "SELECT * FROM register"
        key_data = conn.loadSql(sql)
        return key_data[0]


if __name__ == '__main__':
    import sys

    print(sys.argv)